#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python_learning 
@File ：main.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2025/2/14 上午9:30 
"""

import multiprocessing
import sqlite3

from backend import start_backend, generate_value, value_monitor
from database import DatabaseManager
from frontend import start_frontend


def main():
	data_queue = multiprocessing.Queue()
	task_queue = multiprocessing.Queue()
	value_queue = multiprocessing.Queue()
	trigger_queue = multiprocessing.Queue()

	# 初始化数据库
	db = DatabaseManager("example.db")
	conn = sqlite3.connect("example.db")
	cursor = conn.cursor()
	cursor.execute("CREATE TABLE IF NOT EXISTS data (id INTEGER PRIMARY KEY, value TEXT)")
	cursor.execute("INSERT OR IGNORE INTO data (id, value) VALUES (1, 'initial')")
	conn.commit()
	conn.close()

	# 启动后端进程
	data_reader_process, task_processor_process = start_backend(data_queue, task_queue, "example.db")

	# 启动监控值生成器
	value_generator_process = multiprocessing.Process(target=generate_value, args=(value_queue,))
	value_generator_process.start()

	# 启动监控子进程
	monitored_value = multiprocessing.Value('i', 0)  # 监控值
	monitor_process = multiprocessing.Process(
		target=value_monitor,
		args=(task_queue, value_queue, monitored_value, 3, trigger_queue)
	)
	monitor_process.start()

	# 启动前端进程
	frontend_process = multiprocessing.Process(target=start_frontend, args=(data_queue, task_queue))
	frontend_process.start()

	# 等待所有进程完成
	frontend_process.join()
	value_generator_process.terminate()
	monitor_process.terminate()

	# 终止所有进程
	data_reader_process.terminate()
	task_processor_process.terminate()


if __name__ == "__main__":
	main()
